import { Module } from 'vuex'
import type { ILoginState } from './types'
import type { IRootState } from '../types'
import {
  userLogin,
  getUserInfoById,
  getUserMenusByRoleId
} from '@/service/login/login'
import storage from '@/utils/storage'
import router from '@/router'
import { mapMenusToRoutes, mapMenusToPermissions } from '@/utils/map-routes'
/***
 * Module需要两个泛型类型，<S,R>
 * S是当前模块的state的类型，R是根模块的类型
 */
const LoginModule: Module<ILoginState, IRootState> = {
  namespaced: true,
  state() {
    return {
      token: '',
      userInfo: {},
      userMenus: [],
      permissions: []
    }
  },
  getters: {},
  mutations: {
    setToken(state, token: string) {
      state.token = token
    },
    setUserInfo(state, userInfo: any) {
      state.userInfo = userInfo
    },
    setUserMenus(state, userMenus: any) {
      state.userMenus = userMenus
      // 动态生成用户所拥有的的权限菜单
      const routes = mapMenusToRoutes(userMenus)
      routes.forEach((route) => {
        router.addRoute('main', route)
      })
      const permissions = mapMenusToPermissions(userMenus)

      state.permissions = permissions
    }
  },
  actions: {
    async accountLoginAction({ commit }, payload: any) {
      const loginResult = await userLogin(payload)
      const { id, token } = loginResult.data
      commit('setToken', token)
      storage.setStorage('token', token)
      // 获取用户信息
      const userResult = await getUserInfoById(id)
      commit('setUserInfo', userResult.data)
      storage.setStorage('userInfo', userResult.data)
      // 获取用户权限菜单
      const userMenuResult = await getUserMenusByRoleId(userResult.data.role.id)
      commit('setUserMenus', userMenuResult.data)
      storage.setStorage('userMenus', userMenuResult.data)

      // 跳转到首页
      router.push('/main')
    },
    // 将本地缓存数据设置到vuex
    setLocalData({ commit }) {
      const token = storage.getStorage('token')
      if (token) {
        commit('setToken', token)
      }
      const userInfo = storage.getStorage('userInfo')
      if (userInfo) {
        commit('setUserInfo', userInfo)
      }
      const userMenus = storage.getStorage('userMenus')
      if (userMenus) {
        commit('setUserMenus', userMenus)
      }
    }
  }
}

export default LoginModule
